/*
 * @lc app=leetcode.cn id=946 lang=typescript
 *
 * [946] 验证栈序列
 */

// @lc code=start
function validateStackSequences(pushed: number[], popped: number[]): boolean {
  // 模拟栈
  const stack = new Array<number>();
  const n = pushed.length;
  // popped序列索引
  let i = 0;
  for (const num of pushed) {
    stack.push(num);
    // 检查栈顶元素是否和出栈序列匹配
    while (stack.length && popped[i] === stack.at(-1)) {
      stack.pop();
      i++;
    }
  }
  return stack.length === 0;
}
// @lc code=end
